package com.bupt.uchouten.common.skill;

import com.bupt.uchouten.client.listener.ScreenShakeHandler;
import com.bupt.uchouten.common.entity.EarthquakeEntity;
import com.bupt.uchouten.common.register.UchoutenSounds;
import net.minecraft.client.Minecraft;
import net.minecraft.core.Direction;
import net.minecraft.core.particles.BlockParticleOption;
import net.minecraft.core.particles.ParticleTypes;
import net.minecraft.sounds.SoundEvent;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.level.Level;

import java.util.List;

public class Earthquake extends SkillGenerator {

    public static final float EFFECT_RADIUS = 8f;
    public static final float SPREAD_SPEED = 0.4f;

    private static Earthquake INSTANCE;

    public static Earthquake getInstance() {
        if (INSTANCE == null) {
            INSTANCE = new Earthquake();
        }
        return INSTANCE;
    }

    public Earthquake() {
        super(EarthquakeEntity::new, true);
        this.soundValues(2, 1, 0);
        this.overlap(true);
        this.floor(true);
    }

    @Override
    protected SoundEvent[] createSounds() {
        return new SoundEvent[]{UchoutenSounds.EARTHQUAKE};
    }

    @Override
    protected void addGeneratorExtras(EarthquakeEntity generator, Direction side, LivingEntity caster) {
        // Calculates the lifetime based on the base radius and spread speed
        // Also overwrites the -1 lifetime set due to permanent being true
        generator.lifetime = (int) (EFFECT_RADIUS / SPREAD_SPEED);
    }

    @Override
    protected boolean spawnGenerator(Level world, double x, double y, double z, Direction side, LivingEntity caster) {
        if (world.isClientSide()) {
            world.addParticle(ParticleTypes.EXPLOSION, x, y + 0.1, z, 0, 0, 0);

            double particleX, particleZ;

            for (int i = 0; i < 40; i++) {
                particleX = x - 1.0d + 2 * world.getRandom().nextDouble();
                particleZ = z - 1.0d + 2 * world.getRandom().nextDouble();

                // Original: ParticleTypes.BLOCK_DUST
                world.addParticle(new BlockParticleOption(ParticleTypes.BLOCK, caster.getBlockStateOn()), particleX, y, particleZ, particleX - x, 0, particleZ - z);
            }

            List<Player> entityList = EarthquakeEntity.getEntitiesWithinRadius(15, x, y, z, world, Player.class);

            float intensity = 12f;
            entityList.forEach(player -> {
                if (Minecraft.getInstance().player == player) {
                    ScreenShakeHandler.shakeScreen(intensity);
                }
            });
        }

        return super.spawnGenerator(world, x, y, z, side, caster);
    }

}
